/**
 * @param {string} word1
 * @param {string} word2
 * @return {number}
 */
var minDistance = function (word1, word2) {
  let m = word1.length
  let n = word2.length

  //定义状态数组dp：dp[i][j] 表示将 word1[0..i-1] 转换成 word2[0..j-1] 所需的最小操作数
  const dp = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0))

  //初始化：
  //将 word1 的前 i 个字符变为空串 → 删除 i 次
  for (let i = 0; i <= m; i++) {
    dp[i][0] = i
  }
  //将空串变为 word2 的前 j 个字符 → 插入 j 次
  for (let j = 0; j <= n; j++) {
    dp[0][j] = j
  }

  //状态转移方程
  for (let i = 1; i <= m; i++) {
    for (let j = 1; j <= n; j++) {
      if (word1[i - 1] === word2[j - 1]) {
        dp[i][j] = dp[i - 1][j - 1]
      } else {
        dp[i][j] = 1 + Math.min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1])
      }
    }
  }

  //返回结果
  return dp[m, n]
};